package com.huadao.cart_ccs.common;

import android.content.Context;
import android.content.res.Resources;
import android.os.Handler;
import android.widget.Toast;

import com.huadao.cart_ccs.main.CartApplication;

public class RockToast {
    public RockToast() {
    }

    private static Toast mToast=null;

    private static Resources getResources(){
        return CartApplication.getInstance().getResources();
    }

    //获取文字
    private static String getString(int resId){
        return getResources().getString(resId);
    }

    private static long getMainThreadId(){
        return CartApplication.getMainThreadId();
    }
    //获取主线程handler
    private static Handler getHandler(){
        return CartApplication.getMainThreadHandler();
    }
    //再主线程执行runnable
    private static boolean post(Runnable runnable){
        return getHandler().post(runnable);
    }

    //判断当前线程是不是在主线程
    private static boolean isRunInMainThread(){
        return android.os.Process.myTid()==getMainThreadId();
    }

    //对toast封装，线程安全，可以在非主线程调用
    public static void showToastSafe(int resId){
        showToastSafe(getString(resId));
    }

    //对toast封装，线程安全，可以在非主线程调用
    public static void showToastSafe(final String str){
        if(isRunInMainThread()){
            showToast(str);
        }else {
            post(new Runnable() {
                @Override
                public void run() {
                    showToast(str);
                }
            });
        }
    }

    private static void showToast(String str){
        Context context=CartApplication.getInstance();
        if(context!=null){
            showToast(context,str);
        }
    }

    private static void showToast(Context context,String text){
        if(mToast==null){
            mToast=Toast.makeText(context,text,Toast.LENGTH_SHORT);
        }else {
            mToast.setText(text);
            mToast.setDuration(Toast.LENGTH_SHORT);
        }
        mToast.show();
    }
}
